#include "TrackBase.h"

#include <string.h>
#include <fstream>
#include <iostream>

TrackBase::TrackBase(const char* directory) {
	strcpy(dir, directory);
	if (dir[strlen(dir) - 1] != '/') {
		strcat(dir, "/");
	}
}

bool TrackBase::load(std::string key, std::vector<Track>& tracks) {
	ifstream fin;
	char fileName[256];
	strcpy(fileName, dir);
	strcat(fileName, key.c_str());
	strcat(fileName, BASE_SUFFIX);
	fin.open(fileName);
	if (!fin) {
		std::cout << "Unable to load file " << fileName << "\n";
		return false;
	} else {
		tracks.clear();
		unsigned n;
		while(!fin.eof()) {
			fin >> n;
			tracks.push_back(Track());
			for (unsigned i = 0; i < n && !fin.eof(); i++) {
				int x;
				int y;
				fin >> x >> y;
				tracks.back().addPoint(x, y);
			}
		}
		fin.close();
		return true;
	}
}

bool TrackBase::add(std::string key, const Track& track) {
	ofstream fout;
	char fileName[256];
	strcpy(fileName, dir);
	strcat(fileName, key.c_str());
	strcat(fileName, BASE_SUFFIX);
	fout.open(fileName, std::ios::app);
	if (!fout) {
		std::cerr << "Unable to open save " << fileName << "\n";
		return false;
	} else {
		const vector<Point>& points = track.getPoints();
		std::vector<Point>::const_iterator it;
		for (it = points.begin(); it != points.end(); it++) {
			fout << it->x << " " << it->y << "\n";
		}
		fout.close();
		return true;
	}
}

const std::set<std::string>& TrackBase::keySet() {
	
}

